package com.dis.user.config;

import com.dis.common.utils.JwtTool;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;

@Configuration
public class JwtConfig {

    /**
     * 创建RSA密钥对，用于JWT签名
     */
    @Bean
    @ConditionalOnMissingBean
    public KeyPair keyPair() {
        try {
            // 使用与网关相同的密钥库
            KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(
                    new ClassPathResource("hmall.jks"),
                    "hmall123".toCharArray());
            
            // 获取密钥对
            return keyStoreKeyFactory.getKeyPair("hmall", "hmall123".toCharArray());
        } catch (Exception e) {
            // 如果出现异常，记录日志并返回null
            System.err.println("无法加载密钥库: " + e.getMessage());
            return null;
        }
    }

    /**
     * 创建JwtTool，用于生成和解析JWT
     */
    @Bean
    @ConditionalOnMissingBean
    public JwtTool jwtTool(KeyPair keyPair) {
        if (keyPair == null) {
            return null;
        }
        return new JwtTool(keyPair);
    }
} 